<?php
/**
 * Created by PhpStorm.
 * User: 123
 * Date: 2021/3/31
 * Time: 1:00
 */

namespace app\adminapi\validate;

use app\common\model\Admin;

/**
 * 管理员修改密码验证
 * Class Changepwd
 * @package app\apiadmin\validate
 */
class Changepwd extends Base
{
    protected $rule = [
        'oldpassword' => 'require|max:20|passwordEquality',
        'newpassword' => 'require|max:20',
        'confirmpassword' => 'require|max:20|newpasswordEquality',
    ];

    protected $message = [
        'oldpassword.require' => '旧密码必须',
        'oldpassword.max' => '旧密码不能超过20位',
        'oldpassword.passwordEquality' => '旧密码错误',

        'newpassword.require' => '新密码必须',
        'newpassword.max' => '新密码不能超过20位',

        'confirmpassword.require' => '确认密码必须',
        'confirmpassword.max' => '确认密码不能超过20位',
        'confirmpassword.newpasswordEquality' => '两次输入密码不一致',
    ];

    /**
     * 密码是否正确
     * @param $value
     * @param $rule
     * @param $data
     * @return bool
     * @throws \think\exception\DbException
     */
    protected function passwordEquality($value, $rule, $data)
    {
        $admin = Admin::get(['id' => $data['admin']['admin_id']]);
        if($admin['password']!=Admin::getEncryptPassword($data['oldpassword'], $admin['salt'])) return false;
        return true;
    }

    /**
     * 两次密码是否相同
     * @param $value
     * @param $rule
     * @param $data
     * @return bool
     */
    protected function newpasswordEquality($value, $rule, $data)
    {
        if($value!=$data['newpassword']) return false;
        return true;
    }

}